import 'package:flutter/material.dart';
import '../data/wishlist_repository.dart';
import '../data/product_repository.dart';
import '../entity/game.dart';

class WishlistProvider extends ChangeNotifier {
  final WishlistRepository _wishlistRepository = WishlistRepository();
  final ProductRepository _productRepository = ProductRepository();

  List<Game> _wishlistGames = [];
  List<Game> get wishlistGames => _wishlistGames;

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  Future<void> fetchWishlist(String userId) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    //加载用户愿望单逻辑
    try {
      //根据用户id查询游戏，使用Game.fromMap()创建Game对象列表，此时不会填充products列表。
      final baseGames = await _wishlistRepository.getWishlistGamesForUser(userId);
      final List<Game> richGames = [];
      //为每个游戏加载对应的产品列表
      for (final game in baseGames) {
        final products = await _productRepository.getProductsByGameId(game.id);
        //使用copyWith创建一个包含产品列表的新Game对象副本
        richGames.add(game.copyWith(products: products));
      }
      _wishlistGames = richGames;
    } catch (e) {
      _errorMessage = "加载愿望单失败: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> removeGameFromWishlist(String userId, String gameId) async {
    try {
      await _wishlistRepository.removeFromWishlist(userId, gameId);
      await fetchWishlist(userId); //刷新
    } catch (e) {
      print("从愿望单移除失败: $e");
    }
  }
}
